﻿#!/usr/bin/env python
#coding: utf-8

import os
import sys
import re

from xml.etree import ElementTree

from lib.models.column import *
from lib.exception.file import *
from lib.core.log import logger as log

class XmlParse():
    """
    xml文件解析类
    """
    def __init__(self, xml_file):
        if os.path.exists(xml_file):
            self._xmlDom = ElementTree.parse(xml_file)
            self._root = self._xmlDom.getroot()
        else:
            print("[%s] not found file." % xml_file)
            isCreated = False

    # get children return key,value dictionary
    def getChildren(self, node, xPath):
        item = node.find("./%s" % xPath)
        subitem = item.getchildren()
        result = {}
        for elem in subitem:
            result[elem.tag] = elem.text
        return result

    # get node list
    def getNodeList(self, node, xPath=None):
        if xPath != None:
            return 	node.findall("./%s" % xPath)
        else:
            return self._xmlDom.findall(node)

    def getNodeText(self, node=None, name=None):
        if (node != None) and (name != None):
            return node.find("./%s" % name).text
        else:
            return None
            
class XmlLoader:    
    """
    解析.conf配置文件类 
    """
    @staticmethod
    def getColumns(xml_file):
        result = {}
        if os.path.exists(xml_file):
            log.info("Found configure file [%s]. Loading Configure..." % xml_file)
            xmldom = XmlParse(xml_file)
            for node in xmldom.getNodeList("menu/column"):	
                col = Column(xmldom.getNodeText(node, "name"), xmldom.getNodeText(node, "url"))
                domain = re.compile(r'(http://.*?/)').match(col.url)
                if domain: col.domain = domain.group(1)                    
                pageDic = xmldom.getChildren(node,"page")
                col.page_size = pageDic["size"]
                col.page_file = pageDic["file"]
                col.page_total_regex = re.compile(u'%s' % pageDic["total_regex"])
                for item in xmldom.getNodeList(node, "regex/item"):
                    col.regex[item.get("name")] = item.text.split(",,,")                    
                    regexitem = col.regex[item.get("name")] #当前正则项
                    for i in range(0, len(regexitem)):
                        regexitem[i] = re.compile(r'%s' % regexitem[i])
                        #print regexitem[i] 
                result[col.name] = col
            log.info("Found %s columns. %s " % (len(result), result.keys()))
            return result
        else:
             raise FileNotFoundException("Configure file not found!")